package com.bw.ch.baselib;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.Fragment;

import kotlin.NotImplementedError;

/**
 * Description:
 * Author: conghao
 * Date: 2023/9/17 22:26
 */
public abstract class BaseBindingFragment<VDB extends ViewDataBinding> extends Fragment {

    protected VDB mBinding;
    protected boolean isLazy;

    private boolean isVisibleToUser;
    private boolean hasInit = false;

    public BaseBindingFragment(boolean isLazy) {
        this.isLazy = isLazy;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        if (isLazy && mBinding != null && !hasInit) {
            hasInit = true;
            initView();
            initData();
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mBinding == null) {
            if (getLayout() == 0) {
                throw new NotImplementedError("错误：未实现 getLayout() 方法！");
            }
            mBinding = DataBindingUtil.inflate(inflater, getLayout(), container, false);
            mBinding.setLifecycleOwner(this);
            if (!isLazy) {
                initView();
                initData();
            } else if(isVisibleToUser && !hasInit){
                hasInit = true;
                initView();
                initData();

            }
        }
        return mBinding.getRoot();
    }

    public abstract int getLayout();

    public abstract void initView();

    public abstract void initData();

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mBinding != null) {
            mBinding.unbind();
            mBinding = null;
        }
    }
}
